package com.xunshangwang.pinhaohuo.ui.fragments;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.xunshangwang.pinhaohuo.R;
import com.xunshangwang.pinhaohuo.adapters.GoodsAdapter;
import com.xunshangwang.pinhaohuo.decorations.GoodsItemDecoration;
import com.xunshangwang.pinhaohuo.entity.Banner;
import com.xunshangwang.pinhaohuo.entity.Goods;
import com.xunshangwang.pinhaohuo.entity.GoodsAttr;
import com.xunshangwang.pinhaohuo.http.HttpTool;
import com.xunshangwang.pinhaohuo.http.JsonHttpHandler;
import com.xunshangwang.pinhaohuo.tools.CommonTool;
import com.xunshangwang.pinhaohuo.tools.DebugHelper;
import com.xunshangwang.pinhaohuo.tools.SPHelper;
import com.xunshangwang.pinhaohuo.ui.activities.GoodsDetailActivity;
import com.xunshangwang.pinhaohuo.ui.activities.GoodsListActivity;
import com.xunshangwang.pinhaohuo.widgets.CircleIndicator;
import com.xunshangwang.pinhaohuo.widgets.LMPageRecyclerView;
import com.xunshangwang.pinhaohuo.widgets.RefreshLayout;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import tool.library.adapter.BaseRecyclerAdapter;
import tool.library.widget.AutoCycleViewPager;
import tool.library.widget.LoadRecyclerView;

/**
 * Created by xzp on 16/1/14.
 */
public class HomeFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener,LoadRecyclerView.OnLoadListener,
        BaseRecyclerAdapter.OnItemClickListener{
    private LMPageRecyclerView mRecycler;
    private RefreshLayout mRefresh;
    private AutoCycleViewPager mBannerPager;
    private ViewPager mGoodAttrsPager;
    private HomeAdapter mHomeAdapter;
    private GoodsAttrsAdapter mAttrsAdapter;
    private CircleIndicator mAttrsIndicator,mBannerIndicator;
    private BannerAdapter mBannerAdapter;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_home,container,false);
        mRecycler= (LMPageRecyclerView) view.findViewById(R.id.goods_list_view);
        mRecycler.setLayoutManager(new LinearLayoutManager(inflater.getContext()));
        mHomeAdapter=new HomeAdapter(inflater.getContext());
        mRecycler.setAdapter(mHomeAdapter);
        mHomeAdapter.setOnItemClickListener(this);
        mRecycler.setOnLoadListener(this);
        mRecycler.addItemDecoration(new GoodsItemDecoration(inflater.getContext()){
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int position=parent.getChildAdapterPosition(view);
                if(position>0 && position<mHomeAdapter.getItemCount()-1)
                    super.getItemOffsets(outRect, view, parent, state);
            }
        });
        mAttrsAdapter=new GoodsAttrsAdapter();
        mGoodAttrsPager.setAdapter(mAttrsAdapter);
       // mBannerAdapter=new BannerAdapter();
      //  mBannerPager.setAdapter();
        mAttrsIndicator.setViewPager(mGoodAttrsPager);
        mBannerIndicator.setViewPager(mBannerPager);
        mRefresh= (RefreshLayout) view.findViewById(R.id.refresh_layout);
        mRefresh.setOnRefreshListener(this);
        return view;
    }

    @Override
    public void onRefresh() {
        requestBanner();
        requestGoodsAttrs();
        requestRefresh();
    }

    @Override
    public void onLoad(LoadRecyclerView recyclerView) {
        requestLoadMore();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Handler handler=new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefresh.setRefreshing(true);
                onRefresh();
            }
        }, 200);
        //requestGoodsAttrs();
    }

    @Override
    public void onItemClick(BaseRecyclerAdapter adapter, View item, int position) {
        position=position-1;
//        Intent intent=new Intent(getContext(), GoodsDetailActivity.class);
//        intent.putExtra("id",mHomeAdapter.getList().get(position).getGoods_id());
//        startActivity(intent);
        Intent intent=new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("pin://www.xunshangwang.com/goods/detail?id=" + mHomeAdapter.getList().get(position).getGoods_id()));
        startActivity(intent);
    }

    private void requestBanner(){
        JsonHttpHandler<List<Banner>> handler=new JsonHttpHandler<List<Banner>>() {
            @Override
            public List<Banner> parseData(JSONObject object) throws Throwable {
                return JSON.parseArray(object.getString("banners"),Banner.class);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, List<Banner> response) {
                mBannerAdapter=new BannerAdapter(response);
                mBannerPager.setAdapter(mBannerAdapter);
                //mBannerPager.resetRun();
                mBannerIndicator.notifyDataSetChanged();
                //mBannerAdapter.setList(response);
            }
        };
        handler.setTag(getView());
        HttpTool.get(getContext(), "?g=Api&m=Banner&a=lists", handler);

    }
    private void requestGoodsAttrs(){
        JsonHttpHandler<List<GoodsAttr>> handler=new JsonHttpHandler<List<GoodsAttr>>() {
            @Override
            public List<GoodsAttr> parseData(JSONObject object) throws Throwable {
                return JSON.parseArray(object.getString("attrs"), GoodsAttr.class);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, List<GoodsAttr> response) {

                if(response==null || response.size()==0){
                    mGoodAttrsPager.setVisibility(View.GONE);
                    mAttrsIndicator.setVisibility(View.GONE);
                }
                else {
                    mGoodAttrsPager.setVisibility(View.VISIBLE);
                    mAttrsIndicator.setVisibility(View.VISIBLE);
                    if(response.size()>4){
                        LinearLayout.LayoutParams params= (LinearLayout.LayoutParams) mGoodAttrsPager.getLayoutParams();
                        params.height=CommonTool.dpToPx(getContext(),180);
                        mGoodAttrsPager.requestLayout();
                    }else{
                        LinearLayout.LayoutParams params= (LinearLayout.LayoutParams) mGoodAttrsPager.getLayoutParams();
                        params.height=CommonTool.dpToPx(getContext(),90);
                        mGoodAttrsPager.requestLayout();
                    }
                }
                mAttrsAdapter.setList(response);
                mAttrsAdapter.notifyDataSetChanged();
                mAttrsIndicator.notifyDataSetChanged();
            }
        };
        handler.setTag(getView());
        HttpTool.get(getContext(),"?g=Api&m=Extends&a=getGoodsAttrList",handler);
    }
    private void requestRefresh(){
        JsonHttpHandler<List<Goods>> handler=new JsonHttpHandler<List<Goods>>() {
            @Override
            public List<Goods> parseData(JSONObject object) throws Throwable {
                mRecycler.setCount(object.has("count")?object.getInt("count"):0);
                return JSON.parseArray(object.getString("goods"),Goods.class);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mRefresh.setRefreshing(false);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, List<Goods> response) {
                mHomeAdapter.setList(response);
                mRecycler.resetPage();
            }
        };
        handler.setTag(getView());
        HttpTool.get(getContext(),"?g=Api&m=Goods&a=lists&p=1",handler);
    }
    private void requestLoadMore(){
        JsonHttpHandler<List<Goods>> handler=new JsonHttpHandler<List<Goods>>() {
            @Override
            public List<Goods> parseData(JSONObject object) throws Throwable {
                mRecycler.setCount(object.has("count")?object.getInt("count"):0);
                return JSON.parseArray(object.getString("goods"),Goods.class);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, List<Goods> errorResponse) {
                super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
                mRecycler.loadFinish(false);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, List<Goods> response) {
                mHomeAdapter.addAll(response);
                mRecycler.loadFinish(true);
            }
        };
        handler.setTag(getView());
        HttpTool.get(getContext(),"?g=Api&m=Goods&a=lists&p="+(mRecycler.getPage()+1),handler);
    }
    private class HomeAdapter extends GoodsAdapter{
        private HeadHolder mHeadHolder;
        public HomeAdapter(Context context) {
            super(context);
            View view=LayoutInflater.from(getContext()).inflate(R.layout.home_head,mRecycler,false);
            mHeadHolder=new HeadHolder(view);
        }

        @Override
        public int getItemCount() {
            return super.getItemCount()+1;
        }

        @Override
        public int getViewType(int position) {
            if(position==0)
                return 0;
            else
                return 1;
        }

        @Override
        public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            if(viewType==1)
                return super.onCreateHolder(parent, viewType);
            else {
                return mHeadHolder;
            }
        }
        @Override
        public void onBindHolder(RecyclerView.ViewHolder holder, int position) {
            if(position==0)
                return;
            else
                position=position-1;
            super.onBindHolder(holder, position);
        }
        private class HeadHolder extends RecyclerView.ViewHolder{
            public HeadHolder(View itemView) {
                super(itemView);
                mBannerPager= (AutoCycleViewPager) itemView.findViewById(R.id.home_banner_pager);
                mGoodAttrsPager= (ViewPager) itemView.findViewById(R.id.goods_attr_pager);
                mAttrsIndicator= (CircleIndicator) itemView.findViewById(R.id.good_attr_indicator);
                mBannerIndicator= (CircleIndicator) itemView.findViewById(R.id.home_banner_indicator);
                FrameLayout bannerPanel= (FrameLayout) itemView.findViewById(R.id.home_banner_panel);
                final int bannerPagerHeight= (int) (SPHelper.getIntValue(getContext(),SPHelper.SP_CONFIG,SPHelper.SCREEN_WIDTH_PIXELS)*0.375);
                LinearLayout.LayoutParams params= (LinearLayout.LayoutParams) bannerPanel.getLayoutParams();
                params.height=bannerPagerHeight;
            }
        }
    }

    private class BannerAdapter extends AutoCycleViewPager.CyclePagerAdapter<Banner> implements View.OnClickListener{
        public BannerAdapter(List<Banner> list) {
            super(list);
        }

        @Override
        public void onClick(View view) {
            int position= (int) view.getTag();
            String url=getList().get(position).getTarget_url();
            if(url!=null && url.length()>0){
                try {
                    Intent intent=new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                }catch (Exception e){
                    DebugHelper.i("banner_url_error",e.toString());
                }
            }
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            position=position%getSize();
            ViewGroup bannerView= (ViewGroup) LayoutInflater.from(getContext()).inflate(R.layout.home_banner_item,container,false);
            bannerView.setTag(position);
            ImageView imageView= (ImageView) bannerView.findViewById(R.id.banner_image);
            //imageView.setTag(position);
            ViewGroup.LayoutParams params=new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            container.addView(bannerView,params);
            Glide.with(HomeFragment.this).load(getList().get(position).getImage_url()).centerCrop().into(imageView);
            bannerView.setOnClickListener(this);
            return bannerView;

        }
    }
    private class GoodsAttrsAdapter extends PagerAdapter implements View.OnClickListener{
        List<GoodsAttr> mList;

        public GoodsAttrsAdapter() {
            super();
            mList=new ArrayList<GoodsAttr>();
        }

        @Override
        public int getCount() {
            if(mList==null)
                return 0;
            return (int) Math.ceil(mList.size()/8f);
        }

        public List<GoodsAttr> getList() {
            return mList;
        }

        public void setList(List<GoodsAttr> list) {
            this.mList = list;
        }

        @Override
        public void onClick(View v) {
            int position= (int) v.getTag();
            Intent intent=new Intent(getContext(), GoodsListActivity.class);
            intent.putExtra("attrId",mList.get(position).getAttr_id());
            intent.putExtra("attrName",mList.get(position).getAttr_name());
            startActivity(intent);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view==object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            //return super.instantiateItem(container, position);
            GridLayout gridLayout=new GridLayout(getContext());
            int start=position*8;
            gridLayout.setColumnCount(4);
            int end=(position+1)*8>mList.size()?mList.size():(position+1)*8;
            final int childWidth= SPHelper.getIntValue(getContext(),SPHelper.SP_CONFIG,SPHelper.SCREEN_WIDTH_PIXELS)/4;
            final int childHeight= CommonTool.dpToPx(getContext(),90);
            for(int i=start;i<end;i++){
                View view=LayoutInflater.from(getContext()).inflate(R.layout.goods_attr_item,gridLayout,false);
                view.setTag(i);
                view.setOnClickListener(this);
                ImageView attrImage= (ImageView) view.findViewById(R.id.goods_attr_image);
                TextView  attrNameText= (TextView) view.findViewById(R.id.good_attr_name_text);
                attrNameText.setText(getList().get(i).getAttr_name());
                GridLayout.LayoutParams params=new GridLayout.LayoutParams();
                params.height=childHeight;
                params.width=childWidth;
                gridLayout.addView(view,params);
                Glide.with(getContext()).load(getList().get(i).getAttr_picture()).fitCenter().into(attrImage);
            }
            ViewGroup.LayoutParams params=new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            container.addView(gridLayout,params);
            return gridLayout;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            //super.destroyItem(container, position, object);
            container.removeView((View) object);
        }

        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
        }
    }
}
